package com.company.admin.service.file;

import com.company.admin.common.myException.BizException;
import com.company.admin.dao.file.FileDao;
import com.company.admin.entity.file.AttachFileEntity;
import com.company.admin.resp.file.FileUploadResponse;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 赵成林
 * @date 2019/2/16 22:37
 */
@Service
public class FileService {

    @Autowired
    private FileDao fileDao;

    @Value("${my.upload.imgPath}")
    private String path;
    @Value("${my.ip}")
    private String ip;

    /**
     * 文件的上传与保存
     * @param multipartFiles
     * @param httpServletRequest
     * @param type
     * @return
     */
    public FileUploadResponse upload(MultipartFile[] multipartFiles, HttpServletRequest httpServletRequest,String type) {
        if (multipartFiles == null || multipartFiles.length == 0) {
            throw new BizException(203, "上传的文件为空，请重新选择");
        }
        for (MultipartFile multipartFile : multipartFiles) {
            if (multipartFile.isEmpty()) {
                throw new BizException(203, "包含的有空文件，请重新选择");
            }
        }

        // 开始处理文件
//        String path = "F:/images";
//        path = httpServletRequest.getSession().getServletContext().getRealPath("/images/");
        FileUploadResponse response = new FileUploadResponse();
        List<Long> attachFileIds = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles){
            String fileName = multipartFile.getOriginalFilename();
            String newFileName = new Date().getTime() + fileName.substring(fileName.indexOf("."));
            File targetFile = new File(path);
            if (!targetFile.exists()){
                targetFile.mkdirs();
            }
            try {
                multipartFile.transferTo(new File(path + File.separator + newFileName));
            } catch (IOException e){
                e.printStackTrace();
                throw new BizException(203, "文件上传失败");
            }
//            System.out.println(httpServletRequest.getRequestURL().toString());
//            System.out.println(httpServletRequest.getRequestURI().toString());
//            System.out.println(httpServletRequest.getRemoteHost() + ":"+ httpServletRequest.getServerPort());
            try {
                String url = ip + ":" + httpServletRequest.getServerPort() + "/" +"image" +"/" + newFileName;
                AttachFileEntity entity = new AttachFileEntity();
                entity.setCreateTime(new Date());
                entity.setType(type);
                entity.setUrl(url);
                fileDao.insert(entity);
                attachFileIds.add(entity.getAttachFileId());
            } catch (Exception e){
                throw new BizException(206, "获取当前项目地址出错");
            }
//            String url = InetAddress.getLocalHost().getHostAddress() + ":" + httpServletRequest.getServerPort() + "/" +"image" +"/" + newFileName;

        }
        response.setAtatchFileIds(attachFileIds);
        return response;
    }
}
